///<reference types="cypress" />

// 验证菜单权限
Cypress.Commands.add('validMenus', ($menus, datas) => {
    if (!datas) {
        return;
    }

    let $ = Cypress.$;
    let mainMenus = [];

    $menus.find('>a>.menu-text').each((i, v) => {
        mainMenus.push(v.innerText.trim());
    });

    datas.forEach(item => {
        if (typeof item == 'object') {
            let props = Object.getOwnPropertyNames(item);

            props.forEach(mainName => {
                let subNames = item[mainName];

                let subMenus = [];

                $menus.find(`>a>.menu-text:contains(${mainName})`).parents('li').find('ul>li').each(function () {
                    subMenus.push($(this).find('a').text().trim());
                });

                expect(mainMenus, `验证一级菜单【${mainName}】是否存在`).to.include(mainName);
                expect(subMenus.length, '验证二级菜单数量是否一致').to.equal(subNames.length);

                (subNames || []).forEach(sub => {
                    expect(subMenus, `验证二级菜单【${sub}】是否存在`).to.includes(sub);
                });
            });
        } else {
            expect(mainMenus, `验证菜单项【${item}】是否存在`).to.include(item);
        }
    });
});

Cypress.Commands.add('visitMenu', ($menus, mainMenu, subMenu) => {
    let targetUrl = '';

    if (!subMenu) {
        targetUrl = $menus.find(`>a>.menu-text:contains(${mainMenu})`).parents('a').attr('href');
    } else {
        let subMenus = $menus.find(`>a>.menu-text:contains(${mainMenu})`).parents('li').find('ul>li');

        targetUrl = subMenus.find(`a:contains(${subMenu})`).attr('href');
    }

    cy.visit(targetUrl);
    cy.url().should('contain', targetUrl);
});

Cypress.Commands.add('clickMenu', (mainMenu, subMenu)=>{
    cy.get('ul.nav-list>li').then($menus=>{
        cy.visitMenu($menus, mainMenu, subMenu);
    });
});